package sys

import (
	"context"
	"github.com/gogf/gf/v2/util/gconv"
	"github.com/xuri/excelize/v2"
	"hotgo/api/admin/activityuser"
	"hotgo/internal/model/entity"
	"hotgo/internal/model/input/sysin"
)

// ImportExcel 导入Excel
func (s *sSysActivityUser) ImportExcel(ctx context.Context, in *sysin.ActivityUserImportExcelIn) (res *activityuser.ImportExcelRes, err error) {
	file, err := in.File.Open()
	if err != nil {
		return
	}
	defer file.Close()

	excel, err := excelize.OpenReader(file)
	if err != nil {
		return
	}
	defer excel.Close()

	res = new(activityuser.ImportExcelRes)
	sheetList := excel.GetSheetList()
	data := []entity.ActivityUser{}
	for _, sheet := range sheetList {
		item := new(sysin.ActivityUserImportExcelSheet)
		item.Sheet = sheet
		item.Rows, err = excel.GetRows(sheet)
		if err != nil {
			return nil, err
		}
		res.Sheets = append(res.Sheets, item)
		for k, row := range item.Rows {
			if k == 0 {
				continue
			}
			record := entity.ActivityUser{}
			record.ActivityId = gconv.Int(row[0])
			record.Name = gconv.String(row[1])
			record.Number = gconv.String(row[2])
			record.Phone = gconv.String(row[3])
			record.Area = gconv.String(row[4])
			record.Pb = gconv.String(row[5])
			record.Target = gconv.String(row[6])
			record.IdCard = gconv.String(row[7])
			record.Status = gconv.Int(row[8])
			data = append(data, record)
		}
	}
	_, err = s.Model(ctx).Data(data).Insert()
	return
}
